<template>
  <table-page
    ref="tablePageRef"
    title="标签列表"
    :search-config="searchConfig"
    :columns="tableConfig"
    :data="tableData"
    :loading="loading"
    :pagination-config="paginationConfig"
    :form-config="formConfig"
    :operate-config="operateConfig"
    :default-form-data="getDefaultFormData()"
    @search="handleSearch"
    @reset="handleReset"
    @selection-change="handleSelectionChange"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    @add="handleAdd"
    @edit="handleEdit"
    @delete="handleDelete"
    @batch-delete="handleBatchDelete"
  />
</template>

<script setup>
/**
 * 文章标签管理页面
 *
 * 功能：
 * 1. 标签列表展示与搜索
 * 2. 标签的添加、编辑、删除和批量删除
 * 3. 列表分页与数据加载
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TablePage from '@/components/TablePage/index.vue'
import { searchConfig, tableConfig, operateConfig } from './config/pageConfig'
import { formConfig, getDefaultFormData } from './config/formConfig'
import { tagApi } from '@/api/tag'

// =============== 状态与配置 ===============

/**
 * 组件引用与状态
 */
const tablePageRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const searchParams = ref({})

/**
 * 分页数据
 * 控制列表分页
 */
const pagination = reactive({
  currentPage: 1, // 当前页码
  pageSize: 10, // 每页条数
  total: 0, // 总条数
})

/**
 * 分页配置
 * 传递给表格组件的分页参数
 */
const paginationConfig = computed(() => ({
  total: pagination.total,
  currentPage: pagination.currentPage,
  pageSize: pagination.pageSize,
  pageSizes: [10, 20, 30, 50],
}))

// =============== 方法 ===============

/**
 * 获取标签列表
 * 根据搜索参数和分页配置加载数据
 */
const fetchTagList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchParams.value,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
    }
    const res = await tagApi.getList(params)
    tableData.value = res.records
    pagination.total = res.total
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 * 更新搜索参数并重新加载数据
 * @param {Object} params - 搜索参数
 */
const handleSearch = (params) => {
  searchParams.value = params
  pagination.currentPage = 1
  fetchTagList()
}

/**
 * 重置处理
 * 清空搜索参数并重新加载数据
 */
const handleReset = () => {
  searchParams.value = {}
  pagination.currentPage = 1
  fetchTagList()
}

/**
 * 选择行变化
 * @param {Array} rows - 选中的行数据
 */
const handleSelectionChange = (rows) => {
  console.log('选中行：', rows)
}

/**
 * 每页条数变化
 * @param {number} val - 新的每页条数
 */
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTagList()
}

/**
 * 页码变化
 * @param {number} val - 新的页码
 */
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTagList()
}

/**
 * 新增标签
 * @param {Object} data - 新标签数据
 */
const handleAdd = async (data) => {
  try {
    loading.value = true
    await tagApi.addTag(data)
    ElMessage.success('新增成功')
    fetchTagList()
  } catch (error) {
    console.error('新增标签失败:', error)
    ElMessage.error('新增标签失败')
  } finally {
    loading.value = false
  }
}

/**
 * 编辑标签
 * @param {Object} data - 更新后的标签数据
 */
const handleEdit = async (data) => {
  try {
    loading.value = true
    await tagApi.updateTag(data)
    ElMessage.success('保存成功')
    fetchTagList()
  } catch (error) {
    console.error('编辑标签失败:', error)
    ElMessage.error('编辑标签失败')
  } finally {
    loading.value = false
  }
}

/**
 * 删除标签
 * 删除单个标签
 * @param {Object} row - 要删除的标签
 */
const handleDelete = async (row) => {
  try {
    loading.value = true
    await tagApi.deleteTag([row.id])
    ElMessage.success('删除成功')
    fetchTagList()
  } finally {
    loading.value = false
  }
}

/**
 * 批量删除
 * 删除多个选中的标签
 * @param {Array} rows - 要删除的标签数组
 */
const handleBatchDelete = async (rows) => {
  try {
    loading.value = true
    const ids = rows.map((row) => row.id)
    await tagApi.deleteTag(ids)
    ElMessage.success('删除成功')
    fetchTagList()
    tablePageRef.value?.clearSelection()
  } finally {
    loading.value = false
  }
}

// =============== 生命周期 ===============

/**
 * 页面加载时获取数据
 */
onMounted(() => {
  fetchTagList()
})
</script>

<style lang="scss" scoped>
// 导入主题变量和混合器
@use '@/assets/styles/theme/base.scss' as *;
@use '@/assets/styles/mixins.scss' as *;

/**
 * 标签管理页样式
 * 使用BEM命名规范
 */
.article-tag {
  /**
   * 标签颜色选择器
   */
  &__color-picker {
    display: inline-block;
    width: 24px;
    height: 24px;
    border-radius: $radius-base;
    @include transition(transform);
    cursor: pointer;
    border: 1px solid $border-light;

    &:hover {
      transform: scale(1.1);
    }
  }

  /**
   * 标签预览
   */
  &__tag-preview {
    display: inline-flex;
    align-items: center;
    height: 24px;
    padding: 0 10px;
    font-size: $font-size-small;
    border-radius: $radius-base;
    @include transition(all);

    &:hover {
      transform: translateY(-2px);
      @include box-shadow('light');
    }
  }
}
</style>
